package com.ifreshwing.view.camera;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by ZHJ on 2016/7/12.
 */
public class ImageUtil {
    public static Bitmap getImageFromAssetsFile(Context context, String fileName) {
        if (fileName == null || fileName.equals("")) {
            return null;
        }
        Bitmap image = null;
        if (fileName.contains("/")) {
            image = BitmapFactory.decodeFile(fileName);
        } else {
            if (!fileName.contains(".")) {
                fileName = fileName + ".png";
            }
            AssetManager am = context.getResources().getAssets();
            try {
                InputStream is = am.open(fileName);
                image = BitmapFactory.decodeStream(is);
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return image;

    }

    public static String saveBitmap(Bitmap bitmap, String picName, String dirName) {
        File f = new File(dirName, picName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);//100:不压缩是100，表示压缩率为0
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f.getAbsolutePath();
    }

    public static void saveBitmap(Bitmap bitmap, String picPath) {
        File f = new File(picPath);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);//100:不压缩是100，表示压缩率为0
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static int getScreenWidth(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric.widthPixels; // 屏幕宽度（像素）
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static Bitmap getCircleBitmap(Bitmap bitmap) {

        int d = bitmap.getWidth() > bitmap.getHeight() ? bitmap.getHeight() : bitmap.getWidth();
        Bitmap output = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(output);

        Paint paint = new Paint();
        Rect rect = new Rect((bitmap.getWidth() - d) / 2, (bitmap.getHeight() - d) / 2, (bitmap.getWidth() + d) / 2, (bitmap.getHeight() + d) / 2);

        Rect dest = new Rect(0, 0, d, d);
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 255, 255, 255);
//        Path path = new Path();
//
//        path.addCircle(d / 2, d / 2, d / 2, Path.Direction.CCW);
//
//        canvas.clipPath(path);
//        //在画布上绘制一个圆
        canvas.drawCircle(d / 2, d / 2, d / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, dest, paint);
        bitmap.recycle();
        bitmap = null;

//        saveBitmap(output, Util.getOutputMediaFile().toString() + File.separator + Util.generateFileName() + ".png");
        return output;
    }

    public static Bitmap getRectBitmap(Bitmap bitmap, int width, int height) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(output);

        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, width, height);
        Rect dest = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 255, 255, 255);
        //在画布上绘制一个圆
        canvas.drawRect(rect, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, null, dest, paint);
        bitmap.recycle();
        bitmap = null;
        return output;
    }

    public static Bitmap decodeImageFile(String filePath, View contentView) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.ARGB_4444;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, opt);
        int layoutHeight = contentView.getHeight();
        int layoutWidth = contentView.getWidth();
        float scale = 0f;
        int bitmapHeight = bitmap.getHeight();
        int bitmapWidth = bitmap.getWidth();
        scale = bitmapHeight > bitmapWidth
                ? layoutHeight / (bitmapHeight * 1f)
                : layoutWidth / (bitmapWidth * 1f);
        Bitmap resizeBmp;
        if (scale != 0) {
            int bitmapheight = bitmap.getHeight();
            int bitmapwidth = bitmap.getWidth();
            Matrix matrix = new Matrix();
            matrix.postScale(scale, scale); // 长和宽放大缩小的比例
            resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmapwidth,
                    bitmapheight, matrix, true);
            bitmap.recycle();
            bitmap = null;
        } else {
            resizeBmp = bitmap;
        }
        return resizeBmp;
    }

    public static Bitmap getImageFromAssetsFileResize(Context context, String fileName, int needWidth, int needHeight) {
        if (fileName == null || fileName.equals("")) {
            return null;
        }
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        Bitmap image = null;
        if (fileName.contains("/")) {
            image = BitmapFactory.decodeFile(fileName, o);
        } else {
            if (!fileName.contains(".")) {
                fileName = fileName + ".png";
            }
            AssetManager am = context.getResources().getAssets();
            try {
                InputStream is = am.open(fileName);
                image = BitmapFactory.decodeStream(is, null, o);
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int bitmapHeight = o.outHeight;
        int bitmapWidth = o.outWidth;
        double scaleWidth = 0f;
        double scaleHeight = 0f;
        double scale = 0f;
        scaleWidth = Math.floor((bitmapWidth * 1f) / needWidth);
        scaleHeight = Math.floor((bitmapHeight * 1f) / needHeight);
        scale = scaleHeight > scaleWidth ? scaleHeight : scaleWidth;

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = (int) scale;
        if (fileName.contains("/")) {
            image = BitmapFactory.decodeFile(fileName, o2);
        } else {
            if (!fileName.contains(".")) {
                fileName = fileName + ".png";
            }
            AssetManager am = context.getResources().getAssets();
            try {
                InputStream is = am.open(fileName);
                image = BitmapFactory.decodeStream(is, null, o2);
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return image;

    }

    public static Bitmap getImageFromAssetsFileResizeCenter(Context context, String fileName, int needWidth, int needHeight) {
        if (fileName == null || fileName.equals("")) {
            return null;
        }
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        Bitmap image = null;
        if (fileName.contains("/")) {
            image = BitmapFactory.decodeFile(fileName, o);
        } else {
            if (!fileName.contains(".")) {
                fileName = fileName + ".png";
            }
            AssetManager am = context.getResources().getAssets();
            try {
                InputStream is = am.open(fileName);
                image = BitmapFactory.decodeStream(is, null, o);
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int bitmapHeight = o.outHeight;
        int bitmapWidth = o.outWidth;
        double scaleWidth = 0f;
        double scaleHeight = 0f;
        double scale = 0f;
        scaleWidth = Math.floor((bitmapWidth * 1f) / needWidth);
        scale = scaleWidth;

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = (int) scale;
        if (fileName.contains("/")) {
            image = BitmapFactory.decodeFile(fileName, o2);
        } else {
            if (!fileName.contains(".")) {
                fileName = fileName + ".png";
            }
            AssetManager am = context.getResources().getAssets();
            try {
                InputStream is = am.open(fileName);
                //设置显示图片的中心区域
                BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(is, false);
                image = bitmapRegionDecoder.decodeRegion(new Rect(0, (bitmapHeight-bitmapWidth)/2, bitmapWidth,(bitmapHeight+bitmapWidth)/2), o2);
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return image;

    }
    public static String distinguishImageFrom(String path) {
        if (path.contains("/")) {
            return path;
        } else {
            return "file:///android_asset/" + path;
        }
    }

}
